import fs from 'fs'
import path from 'path'
import Router from 'koa-router'
import bodyPaeser from 'koa-bodyparser'
import { fileURLToPath } from 'url'
//注册路由
export function useRouter(app, controllerDirName = 'controllers') {
  app.use(bodyPaeser())
  let router = new Router()
  let controllerDirPath = path.join(import.meta.url, '../../../', controllerDirName)
  if (fs.existsSync(fileURLToPath(controllerDirPath))) {
    let controllerFileArr = fs.readdirSync(fileURLToPath(controllerDirPath))
      .filter(item => item.endsWith('Controller.js'))
      .map(item => path.join(controllerDirPath, item))
    controllerFileArr.forEach(async item => {
      let { default: objArr } = await  import(item)
      objArr.forEach(item => {
        if (item.method === 'get') router.get(item.url,item.fn)
        if (item.method === 'post') router.post(item.url,item.fn)
        if (item.method === 'put') router.put(item.url,item.fn)
        if (item.method === 'delete') router.delete(item.url,item.fn)
      })
    })
    app.use(router.routes())
  } else {
    console.log('控制器文件未找到')
  }
} 